//
//  HealthGroupViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/7/24.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "HealthGroupViewController.h"

#import "ChatController.h"
#import "ChatViewController.h"

#import "GroupModel.h"

#import "FriendListCell.h"

#import "UIImageView+EMWebCache.h"

@interface HealthGroupViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>

@property (nonatomic, strong) UITableView    * groupTableView;

@property (nonatomic, strong) NSMutableArray * dataSource;
/**装载群名称用来搜索*/
@property (nonatomic, strong) NSMutableArray * groupNameArray;

@property (nonatomic, strong) NSString *friendNum;

/**搜索结果数组*/
@property (nonatomic, strong) NSMutableArray * resultArray;

@property (nonatomic, strong) UISearchBar    * searchBar;

@property (nonatomic, strong) UISearchDisplayController * searchController;

@end

@implementation HealthGroupViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _groupNameArray = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //self.view.backgroundColor = [UIColor redColor];
    // Do any additional setup after loading the view.
    [self reloadDataSource];
    [self creatUI];
    
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self reloadDataSource];
}

- (void)reloadDataSource
{
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    [SVProgressHUD show];
    
    NSDictionary *parameters = @{@"type":@"0",@"employee_id":user.employee_id};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.hxuser.gounp.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"工作群的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            
            [_dataSource removeAllObjects];
            [_groupNameArray removeAllObjects];
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                GroupModel * groupModel = [[GroupModel alloc]init];
                [groupModel setValuesForKeysWithDictionary:dataDic];
                
                [_dataSource addObject:groupModel];
                
                [_groupNameArray addObject:groupModel.group_name];
                
            }
//            self.friendNum = [dictionary objectForKey:@"total"];
            [_groupTableView reloadData];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];

}


- (void)creatUI
{
    //搜索框
    //_searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 44)];
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    
    _searchBar.placeholder = @"搜索";
    
    //_searchBar.backgroundColor = [UIColor greenColor];
    
    //搜索结果展示
    // 用 searchbar 初始化 SearchDisplayController
    // 并把 searchDisplayController 和当前 controller 关联起来
    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchController.delegate = self;
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchController.searchResultsDelegate = self;
    
    //主界面数据展示
    // _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), SCREEN_W, SCREEN_H-64-44) style:UITableViewStyleGrouped];
    _groupTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    
    _groupTableView.backgroundColor = [UIColor whiteColor];
    _groupTableView.dataSource=self;
    _groupTableView.delegate=self;
    
    UINib * nib = [UINib nibWithNibName:@"FriendListCell" bundle:nil];
    
    [_groupTableView registerNib:nib forCellReuseIdentifier:@"ListCell"];
    
    _groupTableView.tableHeaderView = _searchBar;
    _groupTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_groupTableView];
    
    
}

#pragma mark - ---------------------------Search Delegate----------------------------

//只要用户在searchbar中输入内容就会触发该方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    //    for (NSArray *section in _dataSourceArry)
    //    {
    //        //通过谓词过滤数据
    //        NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchString];
    //
    //        NSArray *a = [section filteredArrayUsingPredicate:p];
    //
    //        //实现排序
    //        //self == 排序条件
    //        //NO    == 升序(YES)or降序(NO)
    //        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    //        NSArray *s = [a sortedArrayUsingDescriptors:@[sort]];
    //        NSLog(@"%@", s);
    //        [_resultArray addObjectsFromArray:s];
    //    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString];//用于过滤
    _resultArray = [NSMutableArray arrayWithArray:[_groupNameArray filteredArrayUsingPredicate:predicate]];
    
    return YES;
}


#pragma mark- ------------------------UITableView 代理实现--------------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

//设置rows的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView != _groupTableView)
    {
        return [_resultArray count];
    }
    else
        return [_dataSource count];
    
}


//Cell的相关设置
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell * cell;
    if(tableView != _groupTableView){
        
        static NSString * cellName=@"cell";
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        }

        //cell.imageView.image = [UIImage imageNamed:@"group_header"];
        cell.textLabel.text  = [_resultArray objectAtIndex:indexPath.row];
    }else{
        
        FriendListCell *cell;
        cell = (FriendListCell *)[tableView dequeueReusableCellWithIdentifier:@"ListCell"];
        if (cell == nil) {
            cell = [[FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendListCell"];
        }
        
        GroupModel *groupModel = [_dataSource objectAtIndex:indexPath.row];
        
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:groupModel.workgroup_img]  placeholderImage: [UIImage imageNamed:@"group_header"]];
        cell.friendNameLabel.text = groupModel.group_name;
        
        return cell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

{
    if (tableView != _groupTableView) {
        for (GroupModel *groupModel in _dataSource) {
            if ([_resultArray[indexPath.row] isEqualToString:groupModel.group_name]) {
                ChatController *chatVC = [[ChatController alloc] initWithChatter:groupModel.group_id isGroup:YES];
                chatVC.title = groupModel.group_name;
                chatVC.groupID = groupModel.group_id;
                chatVC.groupType = HealthGroup;
                [self.navigationController pushViewController:chatVC animated:YES];
            }
        }

        
    }
    else {
        GroupModel *groupModel = [_dataSource objectAtIndex:indexPath.row];
        
        ChatController *chatController = [[ChatController alloc] initWithChatter:groupModel.group_id isGroup:YES];
        //    ChatViewController *chatController = [[ChatViewController alloc] initWithChatter:groupModel.group_id isGroup:YES];
        
        chatController.title = groupModel.group_name;
        chatController.groupID = groupModel.group_id;
        chatController.groupType = HealthGroup;
        
        [self.navigationController pushViewController:chatController animated:YES];
        //    [self.navigationControllerpopToRootViewControllerAnimated:YES];
    }
    
    
}


//设置section的title
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(tableView != _groupTableView){
        return @"搜索结果";
    }
    else{
        
        //return [NSString stringWithFormat:@"%c",97+section];
        return nil;
    }
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


@end
